"""
Game item management for automation.
"""
import time

from loguru import logger

from utils.vision_processor import VisionProcess
from utils.state_manager import StateManager
from utils.km_controller import KMController
from config.screen_coordinates import BAG, STORAGE
from utils.path_helper import resource_path


class ItemManager:
    """
    Manages item usage and related functions.
    """

    def __init__(self, state_manager: StateManager,
                 mouse_controller: KMController,
                 vision_processor: VisionProcess
                 ):
        """Initialize item manager."""
        self.state_manager = state_manager
        self.km = mouse_controller
        self.vision = vision_processor
    def _handle_use_gem(self,find_images_result):
        self.km.move_and_click(*find_images_result[0])
        time.sleep(0.5)
        TARGET_TEXTS = [
            "当前生命值：+",
            "攻击速度",
            "金币",
            "暴击伤害"
        ]

        # 遍历OCR结果
        results = self.vision.get_ocr_results(*BAG.gem_select_area)
        logger.info(results)
        for target in TARGET_TEXTS:
            for position, text in results:
                if target in text:
                    self.km.move_and_click(*position)
                    break
        else:
            self.km.move_and_click(*BAG.gem_default_select_coordinate)


    def _handle_click_use(self,find_images_result):
        self.km.move_and_click(*find_images_result[0])
        self.km.move_and_click(*BAG.blank_coordinate)
    def _handle_sell(self,find_images_result):
        for  position in find_images_result:
            self.km.right_click(*position)
            x, y, _ = self.vision.find_text("出售", *BAG.item_sell_area)
            if x >= 0:
                self.km.move_and_click(x, y)
        self.km.return_to_initial_position()


    def _handle_keep_one(self,find_images_result):
        if len(find_images_result) == 1:
            return
        self._handle_sell(find_images_result[1:])

    image_action_map = {
        # 宝石
        resource_path("images/gem_1_qianghua.bmp"): _handle_use_gem,
        resource_path("images/gem_4_shenhua.bmp"): _handle_use_gem,
        resource_path("images/gem_3_jueze.bmp"): _handle_use_gem,
        resource_path("images/gem_2_quanneng.bmp"): _handle_click_use,
        # 属性书
        resource_path("images/book_2_minjiezhishu.png"): _handle_click_use,
        resource_path("images/book_3_zhilizhishu.png"): _handle_click_use,
        resource_path("images/book_1_liliangzhishu.png"): _handle_click_use,
        # 装备
        resource_path("images/equipment_2_emodaofen.png"):_handle_sell,
        resource_path("images/equipment_1_banjia.png"):_handle_sell,
        resource_path("images/equipment_3_fenraozhihuan.png"):_handle_sell,
        resource_path("images/equipment_4_huilanmao.png"):_handle_sell,
        resource_path("images/equipment_5_jixianfaqiu.png"):_handle_sell,
        resource_path("images/equipment_6_kongaozhixin.png"):_handle_sell,
        resource_path("images/equipment_8_shengzheyiwu.png"):_handle_sell,
        resource_path("images/equipment_10_shoulei.png"):_handle_sell,
        resource_path("images/equipment_11_yingjiaogong.png"):_handle_sell,
        resource_path("images/equipment_12_zhenfenbaoshi.png"):_handle_sell,
        resource_path("images/equipment_13_shanbihufu.png"):_handle_sell,
        # 保留的物品
        resource_path("images/equipment_7_lueduozhezhifu.png"):_handle_keep_one,
        resource_path("images/equipment_9_shenmifazhang.png"):_handle_keep_one
    }

    def _handle_storage_slot(self):
        black_images = self.vision.find_all_images(resource_path("images/black.png"), *BAG.bag_search_area)
        logger.info(f"找到空白槽{len(black_images)}个：{black_images}")
        for position in black_images:
            for image_path, _ in self.image_action_map.items():
                movable_item = self.vision.find_all_images(image_path, *STORAGE.storage_search_area)
                if not movable_item:
                    continue
                self.km.mouse_drag(*movable_item[0],  *position)
                time.sleep(0.2)
                break
            else:
                break
    def use_items(self):
        for _ in range(10):
            find_cnt = 0
            for image_path, action in self.image_action_map.items():
                images_result = self.vision.find_all_images(image_path, *BAG.bag_search_area)
                if images_result:
                    find_cnt += 1
                    action(self,images_result)
                    break
            self.km.press_key('f3')
            self._handle_storage_slot()